package pers.wj.springcloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import pers.wj.springcloud.Dao.EmployeeMapper;
import pers.wj.springcloud.entities.Employee;

import java.util.List;

/**
 * 生产者服务提供接口
 *
 * @author wangjie
 * @version V1.0
 * @date 2020/2/28
 */
@RestController
public class EmployeeController
{
	@Autowired
	private EmployeeMapper mapper;

	@Autowired
	private DiscoveryClient client;

	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	//一旦调用服务方法失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
	@HystrixCommand(fallbackMethod = "processHystrix_Get")
	public Employee get(@PathVariable("id") Long id)
	{

		Employee dept = mapper.get(Math.toIntExact(id));
		
		if (null == dept) {
			throw new RuntimeException("该ID：" + id + "没有没有对应的信息");
		}
		
		return dept;
	}

	@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
	public boolean add(@RequestBody Employee dept)
	{
		mapper.save(dept);
		return true;
	}


	@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
	public List<Employee> list()
	{
		return mapper.getAll();
	}



	@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
	public Object discovery()
	{
		List<String> list = client.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = client.getInstances("SPRINGCLOUD-PROVIDER");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.client;
	}

	public Employee processHystrix_Get(@PathVariable("id") Long id)
	{
		return new Employee().setId(Math.toIntExact(id)).setLastName("生产者：该ID：" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭");
	}
}